import time
import tweepy
from tweepy import OAuthHandler
import json

#Sleeping...316709221

def getTweets(api, user_id, output_file, flag):
    if(flag == False):
        try:
            for page in tweepy.Cursor(api.user_timeline, id=user_id, count=50).pages(1):
                for status in page:
                    output_file.write(json.dumps(status._json)+"\n") 
                flag = True
        except tweepy.TweepError, e:
            if 'Rate limit exceeded' in str(e):
                output_file.flush()
                print '1----' + str(e)
                print 'Sleeping...%s' % user_id
                time.sleep(60*5) #Sleep for 5 minutes
                getTweets(api, user_id, output_file, flag)
            elif 'Failed to send request' in str(e):
                output_file.flush()
                print '2----' + str(e)
                print 'sleeping 60*15...%s' % user_id
                time.sleep(60*15)
                getTweets(api, user_id, output_file, flag)
            elif 'Not authorized' in str(e):
                print '3----' + str(e)
                return True
            else:
                output_file.flush()
                print '4----' + str(e)
                print 'sleeping 60*5...%s' % user_id
                time.sleep(60*5)
                getTweets(api, user_id, output_file, True)

def main():
    consumer_key = '...'
    consumer_secret = '...'
    access_token = '...'
    access_token_secret = '...'
    
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    
    api = tweepy.API(auth)
    
    input_file = '/home/ivy/git/Social/Social/file/user_sampling.txt'
    output_file = '/media/ivy/NTFS/_ubuntu_tmp/tweets/tweets_10.txt'
    f = open(output_file, 'w')
    
    count = 0;
    with open(input_file) as hello_file:
        for line in hello_file:
            print str(count) + " --- " + line
            result = getTweets(api, line, f, False)
            count += 1
            if(result == False):
                print "stop --- " + line
                break
            


if __name__ == '__main__':
    main() 
